const log = require('../util/log')
const urlDao = require('../dao/urlDao')
const wordDao = require('../dao/wordDao')
const uwDao = require('../dao/urlWordDao')
const htmlDao = require('../dao/htmlDao')
const upt = require('../task/updatePTask')
const logger = require('log4js').getLogger()

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, (reqJSON, resolve) => {
    var sUrls = reqJSON.urls,
      sHtmls = reqJSON.htmls,
      sWords = reqJSON.words;
    var p2 = new Promise((resolve, reject) => {
      var getWordPromises = []
      sWords.forEach(sWord => {
        sWord = sWord.replace(
          /[^\u4e00-\u9fa5\w\d]/gi, '').toLowerCase();
        if (sWord == '')
          return;
        getWordPromises.push(new Promise((resolve, reject) => {
          wordDao.findByWord(sWord, word => {
            if (word != null)
              resolve(word);
            else {
              word = {
                word: sWord,
                p: 0
              }
              var p1 = new Promise((resolve, reject) => {
                  wordDao.insert(word, () => {
                    resolve(word)
                  }, err => {
                    log(err)
                    reject(err)
                  })
                }),
                p2 = new Promise(resolve => {
                  wordDao.matchContainWord(sWord, words => {
                    var selectUrlwordPromises = [];
                    words.forEach(word => {
                      selectUrlwordPromises.push(new Promise(resolve => {
                        uwDao.matchWordId(word.wordId, uws => {
                          resolve(uws)
                        })
                      }))
                    })
                    Promise.all(selectUrlwordPromises).then(uwss => {
                      resolve(uwss)
                    }).catch(err => {
                      log(err)
                    })
                  })
                });
              Promise.all([p1, p2]).then(result => {
                var word = result[0],
                  uwss = result[1],
                  insertUrlwordPromises = [];
                uwss.forEach(uws => {
                  uws.forEach(uw => {
                    uw.wordId = word.wordId;
                    insertUrlwordPromises.push(new Promise(resolve => {
                      uwDao.insert(uw, () => {
                        upt.add(uw, () => {
                          resolve()
                        })
                      })
                    }))
                  })
                })
                Promise.all(insertUrlwordPromises).then(() => {
                  resolve(word)
                }).catch(err => {
                  log(err)
                })
              }, () => {
                reject()
              }).catch(err => {
                log(err)
              })
            }
          })
        }))
      })
      Promise.all(getWordPromises).then(words => {
        resolve(words)
      }, () => {
        reject()
      }).catch(err => log(err))
    });
    Promise.all([getUrls(sUrls, sHtmls), p2]).then(result => {
      var urls = result[0],
        words = result[1];
      Promise.all(insertUrlWords(urls, words)).then(result => resolve({
        result: 1
      })).catch(err => {
        log(err)
      })
    }, () => {
      resolve({
        result: -1,
        msg: '有异常'
      })
    }).catch(err => {
      log(err)
      resolve({
        result: -1,
        msg: '有异常'
      })
    })
  })
}

function getUrls(sUrls, sHtmls) {
  var getUrlPromises = []
  sUrls.forEach(sUrl => {
    getUrlPromises.push(new Promise(resolve => {
      urlDao.findByUrl(sUrl, url => {
        if (url != null)
          resolve(url);
        else {
          url = {
            url: sUrl,
            p: 0,
            lastVisitedTime: new Date()
          }
          urlDao.insert(url, () => {
            resolve(url)
          })
        }
      })
    }))
  })
  sHtmls.forEach(sHtml => {
    getUrlPromises.push(new Promise(resolve => {
      var html = {
        html: sHtml,
        time: new Date()
      }
      htmlDao.insert(html, () => {
        var url = {
          url: 'https://zoro.site/' + html.htmlId + '.page',
          p: 0
        }
        urlDao.insert(url, () => {
          // logger.debug('[' + __filename + ':' + __line + ']', JSON.stringify(url))
          resolve(url)
        })
      })
    }))
  });
  return new Promise(resolve => {
    Promise.all(getUrlPromises).then(urls => {
      resolve(urls)
    }).catch(err => {
      log(err)
    })
  })
}

function insertUrlWords(urls, words) {
  var updateUrlWordPromises = [],
    url_id_list = [],
    word_id_list = []
  urls.forEach(url => {
    url_id_list.push(url.urlId)
  })
  words.forEach(word => {
    word_id_list.push(word.wordId)
  })
  urls.forEach(url => {
    words.forEach(word => {
      updateUrlWordPromises.push(new Promise(resolve => {
        uwDao.findByUrlIdWordId(url.urlId, word.wordId, uw => {
          if (uw != null) {
            upt.add(uw, () => resolve());
          } else {
            uw = {
              urlId: url.urlId,
              wordId: word.wordId,
              p: 0
            }
            uwDao.insert(uw, () => upt.add(uw, () => resolve()))
          }
        })
      }))
    })
  })
  return updateUrlWordPromises
}